package com.mall.cart.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class RedisUtils {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 判断指定key中的filed是否存在
     *
     * @param key
     * @param field
     * @return true代表存在 false 代表不存在
     */
    public boolean hexists(String key, int field) {
        HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        String obj = hashOperations.get(key, "" + field);
        return null == obj ? false : true;
    }

    /**
     * 数量新增
     *
     * @param key   redis key
     * @param filed hash filed
     * @param num   要增加的数量
     * @return
     */
    public Long hincr(String key, int filed, long num) {
        return stringRedisTemplate.opsForHash().increment(key, "" + filed,  num);
    }

    /**
     * 存储值
     *
     * @param key
     * @param field
     * @param num
     */
    public void hset(String key, int field, long num) {
        stringRedisTemplate.opsForHash().put(key, "" + field, "" + num);
    }

    /**
     * 删除
     *
     * @param key
     * @param field
     * @return
     */
    public Long hdelete(String key, int field) {
        return stringRedisTemplate.opsForHash().delete(key, "" + field);
    }

    public Map<Object, Object> hgetAll(String key) {
        return stringRedisTemplate.opsForHash().entries(key);
    }

}
